﻿using System;
using System.Xml.Serialization;
using Microsoft.SharePoint;

namespace SecurityParser
{
    public class RoleDefinition : DeployableItem
    {
        [XmlAttribute("name")]
        public string Name
        {
            get;
            set;
        }

        [XmlAttribute("description")]
        public string Description
        {
            get;
            set;
        }

        [XmlAttribute("basepermissions")]
        public SPBasePermissions BasePermissions
        {
            get;
            set;
        }

        public void Attach(SPWeb web)
        {
            //if this role should be applied in the current configuration
            if (this.ShouldDeploy())
            {
                //Find the role
                SPRoleDefinition roleDefinition;

                try
                {
                    roleDefinition = web.RoleDefinitions[Name];

                    //role definition already exists

                    //Update it
                    roleDefinition.BasePermissions = BasePermissions;
                    roleDefinition.Description = Description;

                    //Save the changes
                    roleDefinition.Update();
                }
                catch (Exception)
                {
                    //if role definition doesn't exist
                    SPRoleDefinition newRole = new SPRoleDefinition()
                    {
                        BasePermissions = BasePermissions,
                        Name = Name,
                        Description = Description
                    };

                    //add it
                    web.RoleDefinitions.Add(newRole);

                    //Update the web to save the changes
                    web.Update();
                }




            }
        }
    }
}
